<template>
  <div class="health-info">
    <el-form :model="formData" :label-width="labelWidth" class="archive-form">
      <div class="flex">
        <!-- 左侧内容 -->
        <div class="w-2/3 pr-4">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item
                :label="t('healthRecords.healthInfo.fields.currentIllness')"
              >
                <el-input
                  v-model="formData.currentIllness"
                  :placeholder="t('healthRecords.healthInfo.placeholders.none')"
                  :disabled="!isEditing"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                :label="t('healthRecords.healthInfo.fields.surgeryHistory')"
              >
                <el-input
                  v-model="formData.surgeryHistory"
                  :placeholder="
                    t('healthRecords.healthInfo.placeholders.appendicitis')
                  "
                  :disabled="!isEditing"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                :label="t('healthRecords.healthInfo.fields.traumaHistory')"
              >
                <el-input
                  v-model="formData.traumaHistory"
                  :placeholder="t('healthRecords.healthInfo.placeholders.none')"
                  :disabled="!isEditing"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                :label="t('healthRecords.healthInfo.fields.familyHistory')"
              >
                <el-input
                  v-model="formData.familyHistory"
                  :placeholder="
                    t('healthRecords.healthInfo.placeholders.obesity')
                  "
                  :disabled="!isEditing"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                :label="t('healthRecords.healthInfo.fields.allergyHistory')"
              >
                <el-input
                  v-model="formData.allergyHistory"
                  :placeholder="t('healthRecords.healthInfo.placeholders.none')"
                  :disabled="!isEditing"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                :label="t('healthRecords.healthInfo.fields.currentSymptoms')"
              >
                <el-input
                  v-model="formData.currentSymptoms"
                  :placeholder="
                    t('healthRecords.healthInfo.placeholders.fatigue')
                  "
                  :disabled="!isEditing"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 用药史表格 -->
          <div class="medication-history mt-4">
            <h3 class="text-lg font-medium mb-4">
              {{ t("healthRecords.healthInfo.medicationHistory") }}
            </h3>
            <el-table :data="medications" border>
              <el-table-column
                prop="drugName"
                :label="t('healthRecords.healthInfo.medicationTable.drugName')"
                width="200"
              >
                <template #default="{ row }">
                  <el-input
                    v-model="row.drugName"
                    :disabled="!isEditing"
                    :placeholder="
                      t('healthRecords.healthInfo.placeholders.enterDrugName')
                    "
                    class="borderless-input"
                  />
                </template>
              </el-table-column>
              <el-table-column
                prop="usageMethod"
                :label="
                  t('healthRecords.healthInfo.medicationTable.usageMethod')
                "
                width="100"
              >
                <template #default="{ row }">
                  <el-input
                    v-model="row.usageMethod"
                    :disabled="!isEditing"
                    :placeholder="
                      t('healthRecords.healthInfo.placeholders.enterUsage')
                    "
                    class="borderless-input"
                  />
                </template>
              </el-table-column>
              <el-table-column
                prop="doseQuantity"
                :label="
                  t('healthRecords.healthInfo.medicationTable.doseQuantity')
                "
                width="120"
              >
                <template #default="{ row }">
                  <el-input
                    v-model="row.doseQuantity"
                    :disabled="!isEditing"
                    :placeholder="
                      t('healthRecords.healthInfo.placeholders.enterDose')
                    "
                    class="borderless-input"
                  />
                </template>
              </el-table-column>
              <el-table-column
                prop="frequency"
                :label="t('healthRecords.healthInfo.medicationTable.doseUnit')"
                width="140"
              >
                <template #default="{ row }">
                  <el-input
                    v-model="row.doseUnit"
                    :disabled="!isEditing"
                    :placeholder="
                      t('healthRecords.healthInfo.medicationTable.doseUnit')
                    "
                    class="borderless-input"
                  />
                </template>
              </el-table-column>
              <el-table-column
                prop="frequency"
                :label="t('healthRecords.healthInfo.medicationTable.frequency')"
                width="120"
              >
                <template #default="{ row }">
                  <el-input
                    v-model="row.frequency"
                    :disabled="!isEditing"
                    :placeholder="
                      t('healthRecords.healthInfo.placeholders.enterFrequency')
                    "
                    class="borderless-input"
                  />
                </template>
              </el-table-column>
              <el-table-column
                prop="timing"
                :label="t('healthRecords.healthInfo.medicationTable.timing')"
                width="100"
              >
                <template #default="{ row }">
                  <el-input
                    v-model="row.timing"
                    :disabled="!isEditing"
                    :placeholder="
                      t('healthRecords.healthInfo.placeholders.enterTiming')
                    "
                    class="borderless-input"
                  />
                </template>
              </el-table-column>
              <el-table-column
                prop="treatment"
                :label="t('healthRecords.healthInfo.medicationTable.treatment')"
                width="120"
              >
                <template #default="{ row }">
                  <el-input
                    v-model="row.treatment"
                    :disabled="!isEditing"
                    :placeholder="
                      t('healthRecords.healthInfo.placeholders.enterTreatment')
                    "
                    class="borderless-input"
                  />
                </template>
              </el-table-column>
              <el-table-column
                prop="startDate"
                :label="t('healthRecords.healthInfo.medicationTable.startDate')"
                width="140"
              >
                <template #default="{ row, $index }">
                  <el-input
                    v-model="row.startDate"
                    readonly
                    :placeholder="
                      t('healthRecords.healthInfo.placeholders.startDate')
                    "
                    class="borderless-input date-input-field"
                    @click="handleOpenDatePicker($index)"
                  >
                    <template #suffix>
                      <el-icon
                        v-if="isEditing"
                        class="cursor-pointer text-gray-400 hover:text-blue-500"
                      >
                        <Calendar />
                      </el-icon>
                    </template>
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column
                :label="t('healthRecords.healthInfo.medicationTable.actions')"
                fixed="right"
              >
                <template #default="{ $index }">
                  <div
                    class="cursor-pointer text-gray-500 hover:text-red-500"
                    @click="handleDeleteMedication($index)"
                  >
                    <el-icon><Delete /></el-icon>
                  </div>
                </template>
              </el-table-column>
            </el-table>
            <div class="mt-4">
              <el-button @click="handleAddMedication">
                + {{ t("healthRecords.healthInfo.buttons.add") }}
              </el-button>
            </div>
          </div>
        </div>

        <!-- 右侧内容 -->
        <div class="w-1/3 pl-4">
          <!-- 既往病史 -->
          <el-form-item
            :label="t('healthRecords.healthInfo.fields.pastIllness')"
          >
            <el-input
              v-model="formData.pastIllness"
              type="textarea"
              :rows="3"
              :placeholder="
                t('healthRecords.healthInfo.placeholders.hypertension')
              "
              :disabled="!isEditing"
            />
          </el-form-item>
        </div>
      </div>

      <!-- 底部按钮 -->
      <div class="flex justify-end mt-4 gap-4">
        <el-button @click="handleEdit">{{
          t("healthRecords.healthInfo.buttons.edit")
        }}</el-button>
        <el-button type="primary" @click="handleSave">{{
          t("healthRecords.healthInfo.buttons.save")
        }}</el-button>
      </div>
    </el-form>

    <!-- 时间选择器弹窗 -->
    <!-- 简化弹窗，不显示头部 -->
    <el-dialog
      v-model="showDatePicker"
      width="400px"
      :close-on-click-modal="false"
      :close-on-press-escape="true"
      destroy-on-close
      center
      :title="'选择用药开始时间'"
      class="no-header-dialog"
    >
      <div class="date-picker-content">
        <el-date-picker
          v-model="tempDate"
          type="date"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          class="w-full"
          :clearable="true"
          :editable="false"
        />
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleConfirmDatePicker">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import type { HealthArchiveHealthInfo } from "@/api/health";
import { healthApi } from "@/api/health";
import { Calendar, Delete } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { computed, reactive, ref, watch } from "vue";
import { useI18n } from "vue-i18n";

const props = defineProps<{
  archiveInfo?: HealthArchiveHealthInfo;
  requestSource?: number;
}>();

const emit = defineEmits<{
  (e: "update-success"): void;
}>();

// 国际化
const { t, locale } = useI18n();

// 是否处于编辑状态
const isEditing = ref(false);

// 时间选择器弹窗相关状态
const showDatePicker = ref(false); // 控制日期选择器弹窗显示
const currentEditingIndex = ref(-1); // 当前正在编辑的用药记录索引
const tempDate = ref(""); // 临时保存选择的日期

// 根据语言状态动态调整label宽度
const labelWidth = computed(() => {
  // 英文状态下为130px，中文状态下为110px
  return locale.value === "en" ? "140px" : "110px";
});

// 表单数据
const formData = reactive<HealthArchiveHealthInfo>({
  archiveId: 0,
  currentIllness: "",
  pastIllness: "",
  familyHistory: "",
  currentSymptoms: "",
  allergyHistory: "",
  surgeryHistory: "",
  traumaHistory: "",
  medications: []
});

// 用药史数据
const medications = computed(() => formData.medications || []);

// 监听props变化，更新表单数据
watch(
  () => props.archiveInfo,
  (newVal, oldVal) => {
    if (newVal) {
      console.log("健康信息数据更新:", {
        新数据: newVal,
        旧数据: oldVal,
        数据来源: props.requestSource
      });

      // 更新表单数据，确保用药史数组正确初始化
      Object.assign(formData, {
        ...newVal,
        medications: newVal.medications || []
      });

      console.log("健康信息表单数据已更新:", {
        基础信息: {
          currentIllness: formData.currentIllness,
          pastIllness: formData.pastIllness,
          familyHistory: formData.familyHistory,
          allergyHistory: formData.allergyHistory,
          surgeryHistory: formData.surgeryHistory,
          traumaHistory: formData.traumaHistory,
          currentSymptoms: formData.currentSymptoms
        },
        用药史数量: formData.medications?.length || 0,
        档案ID: formData.archiveId
      });
    } else {
      console.log("未接收到健康信息数据");
    }
  },
  { immediate: true }
);

// 编辑按钮点击事件
const handleEdit = () => {
  isEditing.value = true;
  ElMessage.success(t("healthRecords.healthInfo.messages.editMode"));

  console.log("健康信息编辑模式已开启");
};

// 验证表单数据
const validateForm = () => {
  // 验证必填字段
  if (!formData.archiveId) {
    ElMessage.error(t("healthRecords.healthInfo.messages.archiveIdRequired"));
    return false;
  }

  // 验证用药记录
  if (formData.medications?.length) {
    for (const medication of formData.medications) {
      if (!medication.drugName?.trim()) {
        ElMessage.error(
          t("healthRecords.healthInfo.messages.drugNameRequired")
        );
        return false;
      }
      if (!medication.usageMethod?.trim()) {
        ElMessage.error(t("healthRecords.healthInfo.messages.usageRequired"));
        return false;
      }
      if (!medication.doseQuantity?.trim()) {
        ElMessage.error(t("healthRecords.healthInfo.messages.doseRequired"));
        return false;
      }
      if (!medication.frequency?.trim()) {
        ElMessage.error(
          t("healthRecords.healthInfo.messages.frequencyRequired")
        );
        return false;
      }
      if (!medication.timing?.trim()) {
        ElMessage.error(t("healthRecords.healthInfo.messages.timingRequired"));
        return false;
      }
      if (!medication.treatment?.trim()) {
        ElMessage.error(
          t("healthRecords.healthInfo.messages.treatmentRequired")
        );
        return false;
      }
    }
  }

  return true;
};

// 保存按钮点击事件
const handleSave = async () => {
  try {
    // 表单验证
    console.log("开始验证健康信息表单");
    if (!validateForm()) {
      console.log("健康信息表单验证失败");
      return;
    }
    console.log("健康信息表单验证通过");

    // 显示加载状态
    const loading = ElMessage({
      message: t("healthRecords.healthInfo.messages.saving"),
      duration: 0,
      type: "info"
    });

    // 准备提交的数据，排除不属于HealthArchiveHealthInfo的字段
    const submitData: HealthArchiveHealthInfo = {
      archiveId: formData.archiveId,
      currentIllness: formData.currentIllness,
      pastIllness: formData.pastIllness,
      familyHistory: formData.familyHistory,
      currentSymptoms: formData.currentSymptoms,
      allergyHistory: formData.allergyHistory,
      surgeryHistory: formData.surgeryHistory,
      traumaHistory: formData.traumaHistory,
      medications: formData.medications?.map(item => ({
        ...item,
        // 确保 startDate 为字符串格式，符合接口要求
        // 将 startDate 转换为毫秒级字符串（如果有值），否则为空字符串
        startDate: item.startDate ? new Date(item.startDate).getTime() : "",
        dataType: 3, // 健康档案-健康信息
        dataId: formData.archiveId
      })),
      archiveHealthInfoId: formData.archiveHealthInfoId,
      requestSource: props.requestSource
    };

    console.log("准备提交的健康信息数据:", {
      基础字段: {
        archiveId: submitData.archiveId,
        archiveHealthInfoId: submitData.archiveHealthInfoId
      },
      健康信息: {
        currentIllness: submitData.currentIllness,
        pastIllness: submitData.pastIllness,
        familyHistory: submitData.familyHistory,
        allergyHistory: submitData.allergyHistory,
        surgeryHistory: submitData.surgeryHistory,
        traumaHistory: submitData.traumaHistory,
        currentSymptoms: submitData.currentSymptoms
      },
      用药史: submitData.medications,
      请求来源: props.requestSource
    });

    // 调用保存接口
    const response = await healthApi.getHealthArchiveUpdateHealth(submitData);

    // 关闭加载提示
    loading.close();

    console.log("健康信息保存接口响应:", response);
    isEditing.value = false;

    emit("update-success");
  } catch (error: any) {
    console.error("保存健康信息时发生异常:", {
      错误信息: error.message,
      错误堆栈: error.stack,
      当前数据: formData,
      用药史: formData.medications
    });
    ElMessage.error(t("healthRecords.healthInfo.messages.saveFailedRetry"));
  }
};

// 添加用药记录
const handleAddMedication = () => {
  console.log("准备添加用药记录", {
    编辑状态: isEditing.value,
    当前用药史数量: formData.medications?.length || 0,
    档案ID: formData.archiveId
  });

  if (!isEditing.value) {
    console.log("未处于编辑状态，无法添加用药记录");
    ElMessage.error(t("healthRecords.healthInfo.messages.pleaseEdit"));
    return;
  }

  formData.medications = formData.medications || [];

  const newMedication = {
    dataType: 3, // 健康档案-健康信息
    dataId: formData.archiveId,
    drugName: "",
    usageMethod: "",
    doseQuantity: "",
    doseUnit: "",
    frequency: "",
    timing: "",
    startDate: "",
    treatment: ""
  };

  formData.medications.push(newMedication);

  console.log("已添加新的用药记录", {
    新记录: newMedication,
    更新后用药史数量: formData.medications.length,
    所有用药史: formData.medications
  });
};

// 删除用药记录
const handleDeleteMedication = (index: number) => {
  console.log("准备删除用药记录", {
    删除索引: index,
    编辑状态: isEditing.value,
    当前用药史数量: formData.medications?.length || 0,
    要删除的记录: formData.medications?.[index]
  });

  if (!isEditing.value) {
    console.log("未处于编辑状态，无法删除用药记录");
    ElMessage.error(t("healthRecords.healthInfo.messages.pleaseEdit"));
    return;
  }

  if (
    !formData.medications ||
    index < 0 ||
    index >= formData.medications.length
  ) {
    console.error("删除用药记录失败：无效的索引", {
      索引: index,
      用药史长度: formData.medications?.length || 0
    });
    ElMessage.error("删除失败：无效的用药记录");
    return;
  }

  const deletedMedication = formData.medications[index];
  formData.medications.splice(index, 1);

  console.log("已删除用药记录", {
    已删除的记录: deletedMedication,
    更新后用药史数量: formData.medications.length,
    剩余用药史: formData.medications
  });

  ElMessage.success(t("healthRecords.healthInfo.messages.deleteSuccess"));
};

// 打开日期选择器弹窗
const handleOpenDatePicker = (index: number) => {
  if (!isEditing.value) {
    console.log("未处于编辑状态，无法修改开始时间");
    ElMessage.error(t("healthRecords.healthInfo.messages.pleaseEdit"));
    return;
  }

  currentEditingIndex.value = index;
  tempDate.value = formData.medications?.[index]?.startDate || "";
  showDatePicker.value = true;

  console.log("日期选择器弹窗已打开", {
    临时日期: tempDate.value,
    编辑索引: currentEditingIndex.value
  });
};

// 确认日期选择
const handleConfirmDatePicker = () => {
  if (currentEditingIndex.value < 0 || !formData.medications) {
    console.error("确认日期时出错：无效的编辑索引");
    ElMessage.error("操作失败：无效的用药记录");
    return;
  }

  const originalDate =
    formData.medications[currentEditingIndex.value]?.startDate;
  // 更新用药记录的开始时间
  if (formData.medications[currentEditingIndex.value]) {
    formData.medications[currentEditingIndex.value].startDate = tempDate.value;
  }

  // 关闭弹窗并重置状态
  showDatePicker.value = false;
  currentEditingIndex.value = -1;
  tempDate.value = "";
};

// 取消日期选择
const handleCancelDatePicker = () => {
  console.log("取消日期选择", {
    编辑索引: currentEditingIndex.value,
    临时日期: tempDate.value
  });

  // 关闭弹窗并重置状态，不保存任何更改
  showDatePicker.value = false;
  currentEditingIndex.value = -1;
  tempDate.value = "";
};
</script>

<style lang="scss" scoped>
.health-info {
  padding: 20px 0;

  .archive-form {
    .el-form-item {
      margin-bottom: 18px;
    }

    :deep(.el-input),
    :deep(.el-select),
    :deep(.el-date-picker) {
      width: 100%;
    }
  }

  .medication-history {
    h3 {
      color: #303133;
    }

    :deep(.borderless-input) {
      .el-input__wrapper {
        box-shadow: none !important;
        padding: 0;
        background: transparent;
      }

      .el-input__inner {
        border: none;
        padding: 0;
        height: 32px;
        line-height: 32px;

        &:focus {
          box-shadow: none;
        }

        &:disabled {
          background: transparent;
        }
      }
    }

    :deep(.el-table) {
      .el-table__cell {
        padding: 8px;
      }
    }

    // 日期输入框样式
    :deep(.date-input-field) {
      .el-input__wrapper {
        cursor: pointer;

        &:hover {
          box-shadow: 0 0 0 1px
            var(--el-input-hover-border, var(--el-border-color-hover)) inset;
        }
      }

      .el-input__inner {
        cursor: pointer;
      }
    }
  }

  // 日期选择器弹窗样式
  :deep(.el-dialog) {
    border-radius: 8px;

    .el-dialog__header {
      border-bottom: 1px solid #f0f0f0;
      padding: 20px 24px 16px;

      .el-dialog__title {
        font-size: 18px;
        font-weight: 600;
        color: #303133;
      }
    }

    .el-dialog__body {
      padding: 24px;
    }

    .el-dialog__footer {
      border-top: 1px solid #f0f0f0;
      padding: 16px 24px 20px;
    }
  }

  .date-picker-content {
    .el-date-editor {
      font-size: 14px;

      .el-input__wrapper {
        border: 1px solid #dcdfe6;
        border-radius: 6px;
        transition: all 0.3s;

        &:hover {
          border-color: #409eff;
        }

        &.is-focus {
          border-color: #409eff;
          box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
        }
      }
    }
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;

    .el-button {
      padding: 8px 20px;
      border-radius: 6px;
      font-size: 14px;
      transition: all 0.3s;

      &:hover {
        transform: translateY(-1px);
      }
    }
  }
}
</style>
